package com.zzyl.nursing.service.impl;

import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.List;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-12
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

//    @Autowired
//    private WatchService watchService;

    @Autowired
    private TokenService tokenService;



    private static final String WX_OPEN_ID_APPID = "wx67eb2ff837fbb66d";

    private static final String WX_OPEN_ID_SECRET = "71212b1b58b4ae7d21ae9aa65355d560";

    private static final String WX_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session ";

    private static final String WX_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private static final String WX_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";


    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {

        //1.根据code调用微信api获取apenId
       String openId = getOneId(userLoginRequestDto);
        //2.根据openId查询数据库获取用户信息family_member表
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId,openId));
        //3.判断用户信息是否存在，如果不存在，则新增family_member表
        if (ObjectUtil.isEmpty(familyMember)){
            familyMember.setOpenId(openId);
        }
        //4.调用微信api获取用户绑定手机号
        String phoneNumber = getPhone(userLoginRequestDto.getPhoneCode());
        //5.新增或者修改family_member表数据
        insertOrUpdateFamilyMember(familyMember,phoneNumber);
        //6.将用户id存入token中，并返回数据给前端
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", familyMember.getId());
        String token = tokenService.createToken(paramMap);
        LoginVo loginVo = new LoginVo(token, familyMember.getName());
        return loginVo;
    }

    /**
     *  新增或者修改
     * @param familyMember
     * @param phoneNumber
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phoneNumber) {
        if (ObjectUtils.isEmpty(familyMember.getId())){
            //新增
            familyMember.setPhone(phoneNumber);//手机号
            String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                    + StringUtils.substring(familyMember.getPhone(), 7);
            familyMember.setName(nickName);
            save(familyMember);

        }else {
            //修改
            if (!familyMember.getPhone().equals(phoneNumber)){
                familyMember.setPhone(phoneNumber);
            }
            updateById(familyMember);
        }
    }

    /**
     *  获取手机号
     * @param phoneCode
     * @return
     */
    private String getPhone(String phoneCode) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", phoneCode);
        HttpResponse response = HttpUtil.createPost(WX_PHONE_URL + getAccessToken())
                .body(JSONUtil.toJsonStr(paramMap))
                .execute();
        String body = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String str = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        return str;

    }

    /**
     *  获取accessToken
     * @return
     */
    private String getAccessToken() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("grant_type", "client_credential");
        paramMap.put("appid", WX_OPEN_ID_APPID);
        paramMap.put("secret", WX_OPEN_ID_SECRET);
        String result = HttpUtil.get(WX_TOKEN_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String accessToken = (String) jsonObject.get("access_token");
        return accessToken;
    }

    /**
     * 根据code获取openId
     * @param userLoginRequestDto
     * @return
     */
    private String getOneId(UserLoginRequestDto userLoginRequestDto) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", WX_OPEN_ID_APPID);
        paramMap.put("secret", WX_OPEN_ID_SECRET);
        paramMap.put("js_code", userLoginRequestDto.getCode());
        paramMap.put("grant_type", "authorization_code");
        String result = HttpUtil.get(WX_OPEN_ID_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return (String) jsonObject.get("openid");
    }
}
